package com.blankland.dataanalysis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blankland.dataanalysis.domain.Role;
import com.blankland.dataanalysis.domain.User;
import com.blankland.dataanalysis.domain.UserRole;
import com.blankland.dataanalysis.domain.vo.UserRoleVO;
import com.blankland.dataanalysis.result.Result;
import com.blankland.dataanalysis.service.RoleService;
import com.blankland.dataanalysis.service.UserRoleService;
import com.blankland.dataanalysis.service.UserService;
import com.blankland.dataanalysis.utls.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.Inet4Address;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/admin/system/sysUser")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 分页+条件查询
     * @param pageNum 当前页
     * @param pageSize 一页显示几条数据
     * @param username 用户名
     * @return
     */
    @ApiOperation("分页查询+条件查询")
    @GetMapping("/findUserByPageAndCond")
    public Result findUserByPageAndCond(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") String username){

        //分页对象
        Page<User> userPage = new Page<>(pageNum,pageSize);
        //分页查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("username",username);
        wrapper.orderByDesc("id");//倒序
        //分页查询+模型查询
        Page<User> page = userService.page(userPage, wrapper);
        return Result.ok(page);
    }

    /**
     * 根据id查询User
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询User")
    @GetMapping("/findUserById/{id}")
    public Result findUserById(@PathVariable String id){
        User user = userService.getById(id);
        return Result.ok(user);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @ApiOperation(value = "添加User")
    @PostMapping("/saveUser")
    public Result saveUser(User user){
        //添加用户的时候，密码设置MD5加密
        String password = user.getPassword();
        String encrypt = MD5.encrypt(password);
        user.setPassword(encrypt);

        boolean flag = userService.save(user);
        if (true == flag){
            return Result.ok();
        }else {
            return Result.fail();
        }

    }

    /**
     * 更新用户
     * @return
     */
    @ApiOperation(value = "更新User")
    @PutMapping("/updateUser")
    public Result updateUser(User user){
        String password = user.getPassword();
        String encrypt = MD5.encrypt(password);
        user.setPassword(encrypt);
        boolean flag = userService.updateById(user);
        if (true == flag) {
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    /**
     * 删除用户
     * @return
     */
    @ApiOperation(value = "删除User")
    @DeleteMapping("/deleteUser/{id}")
    public Result deleteUser(@PathVariable String id){
        boolean flag = userService.removeById(id);
        if (true == flag){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }


    @ApiOperation(value = "更新用户状态")
    @PutMapping("/updateUserStatus/{id}/{status}")
    public Result updateUserStatus(@PathVariable Long id,
                                   @PathVariable Integer status){
        User user = userService.getById(id);
        user.setStatus(status);
        userService.updateById(user);
        return Result.ok();
    }


    /**
     * 1、从sys_role表中，获取所有的角色数据
     * 2、从sys_user_role表中，通过user_id获取所有的role_id
     * @param userId
     * @return
     */
    @ApiOperation(value = "获取所有角色数据 + 根据userId获取已经分配的roleIds ")
    @GetMapping("/getRolesByUserId/{userId}")
    public Result getRolesByUserId(@PathVariable Integer userId){
        //1、获取所有角色数据
        List<Role> roleList = roleService.list();
        //2、在sys_user_role表中，根据user_id获取对应的role_id
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.select("role_id");
        List<UserRole> userRoleList = userRoleService.list(wrapper);
        //3、只要role_id
        List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("allRoles",roleList);
        resultMap.put("userRoleIds",roleIds);
        return Result.ok(resultMap);
    }

    @ApiOperation("根据用户id，为用户分配角色")
    @PostMapping("/setRoleByUserId")
    public Result setRoleByUserId(@RequestBody UserRoleVO userRoleVO){
        //1、根据userId删除之前一句分配好的角色
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userRoleVO.getUserId());
        userRoleService.remove(wrapper);

        //2、从userRoleVO中获取userId和所有的Role的id，添加到sys_user_role表中
        List<Long> roleIdList = userRoleVO.getRoleIdList();
        for (Long roleId : roleIdList) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userRoleVO.getUserId());
            userRole.setRoleId(roleId);
            userRoleService.save(userRole);
        }
        return Result.ok();
    }
}

